package com.cskaoyan.market.controller.admin;

import com.cskaoyan.market.db.domain.MarketAddress;
import com.cskaoyan.market.service.MarketAdminAddressService;
import com.cskaoyan.market.service.impl.MarketAdminAdminAddressServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("admin/address")
public class AdminAddressController{
    @Autowired
    MarketAdminAddressService marketAdminAddressService ;

    @GetMapping("list")
    private Object list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /**
         * 参数解析
         */
        String pageStr = req.getParameter("page");
        String limitStr = req.getParameter("limit");
        String name = req.getParameter("name");
        String userIdStr = req.getParameter("userId");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");

        /**
         * 参数校验
         */
        int page = 0;
        int limit = 0;
        Integer userId;

        // userId可以为空，若转型失败应捕捉异常，赋值为null
        try {
            userId = Integer.parseInt(userIdStr);
        } catch (NumberFormatException e) {
            userId = null;
        }

        // page、limit均不得为空--为空则往请求体写入错误信息，结束方法
        try {
            page = Integer.parseInt(pageStr);
            limit = Integer.parseInt(limitStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return ResponseUtil.badArgumentValue();
        }

        // sort、order不得为空--设置缺省值
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }

        /**
         * 通过校验，调用service层
         */
        List<MarketAddress> marketAddressList = marketAdminAddressService.list(page, limit, name, userId, sort, order);

        /**
         * 设置响应体
         */
        return ResponseUtil.okList(marketAddressList);

    }
}
